package com.air.ota.util;

public class HexStringUtil {

	public static byte hexStringToByte(String hexString){
		return hexStringToBytes(hexString)[0];
	}
	
	public static byte[] hexStringToBytes(String hexString) {

        if (hexString == null || hexString.equals("")) {

            return null;

        }

        hexString = hexString.toUpperCase();

        int length = hexString.length() / 2;

        char[] hexChars = hexString.toCharArray();

        byte[] d = new byte[length];

        for (int i = 0; i < length; i++) {

            int pos = i * 2;

            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));

        }

        return d;

    }

	public static String bytesToHexString(byte[] src){

        StringBuilder stringBuilder = new StringBuilder("");

        if (src == null || src.length <= 0) {

            return null;

        }

        for (int i = 0; i < src.length; i++) {
        	/*
            int v = src[i] & 0xFF;

            String hv = Integer.toHexString(v);

            if (hv.length() < 2) {

                stringBuilder.append(0);

            }*/
        	String hv = byteToHexString(src[i]);

            stringBuilder.append(hv);

        }

        return stringBuilder.toString().toUpperCase();
    }
	
	public static String byteToHexString(byte src){
		int v = src & 0xFF;
		String hv = Integer.toHexString(v);
		if (hv.length() < 2) {
			hv = "0"+hv;
        }
		return hv;
	}
	
	 private static byte charToByte(char c) {
		 
	        return (byte) "0123456789ABCDEF".indexOf(c);
		 
	 }
	 
	 public static String asc2Hex(String src){
		 byte[] byteArray=src.getBytes();
		 
		 String hexStr ="";
		 for(byte aByte:byteArray){
			 String aHexStr = Integer.toHexString(aByte);
			 if (aHexStr.length()<2){
				 aHexStr = "0"+aHexStr;
			 }
			 hexStr += aHexStr;
		 }
		 return hexStr;
	 }
	 
	 public static String hex2Asc(String src){
		 byte[] hexBytes=hexStringToBytes(src);
		 String ascString ="";
		 for(byte aByte:hexBytes){
			 char aChar=(char)aByte;
			 ascString += aChar+"";
		 }
		 
		 return ascString;
	 }
	 
}
